package com.itheima.web.controller.system;

import com.itheima.domain.system.User;
import com.itheima.web.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/system/user")
public class UserServlet extends BaseServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if ("login".equals(operation)) {
            login(request, response);
        } else if ("logout".equals(operation)) {
            logout(request, response);
        } else if ("changePassWord".equals(operation)) {
            changePassWord(request, response);
        } else if ("updatePassWord".equals(operation)) {
            updatePassWord(request, response);
        }
    }

    private void updatePassWord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
    }

    private void changePassWord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户登录时输入的密码
        String oldpassword = request.getParameter("password");
        //将旧密码传到前台进行比对
        request.setAttribute("oldpass", oldpassword);
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-changepassword.jsp").forward(request, response);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userService.login(username, password);

        if (user != null) {
            request.getSession().setAttribute("user", user);
            //将用户登录时输入的密码存入到请求域中,方便修改密码时能够获取到旧密码,因为数据库中的密码已加密
            request.setAttribute("password", password);
            request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "用户名或密码错误!");
            request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
        }
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("user");
        request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
